package pers.gxm.security.hello.filter;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import pers.gxm.security.hello.pojo.LoginUser;
import pers.gxm.security.hello.utils.JwtUtil;
import pers.gxm.security.hello.utils.RedisCache;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private RedisCache redisCache;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
//      TODO    1   获取请求头中的token
        String token = request.getHeader("Authorization");
//        注意此处需要判断token是否为空，如果为空应该让其放行，因为考虑到一些请求无需token就可以进行响应
//        而且必须进行return!
        if(!StringUtils.hasText(token)){
            filterChain.doFilter(request,response);
            return;
        }
//      TODO    2   将对应token解析为原数据，比如说这里是userid
        String userId;
        try {
            Claims claims = JwtUtil.parseJWT(token);
             userId = claims.getSubject();

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token很奇怪！非法！");
        }


//      TODO    3   根据id去redis查找对应的LoginUser对象
        String redisKey = "login" + userId;
        LoginUser loginUser =  (LoginUser) redisCache.getCacheObject(redisKey);
        if(loginUser == null){
            throw new RuntimeException("redis中未保存此用户");
        }

//      TODO    4   将LoginUser对象放入SecurityContextHolder
//      TODO    4.1 这里还会将LoginUser中的权限赋值到authenticationToken
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
//        TODO  5   放行
        filterChain.doFilter(request,response);
    }
}
